<template>
    <view class="content">
        <van-nav-bar title="取消预约" left-arrow @click-left="onClickLeft" id="navBar"></van-nav-bar>
        <scroll-view class="scroll-content" scroll-y :lower-threshold="80" @scroll="scrollPage" show-scrollbar="false">
            <view class="pageTop">
                取消说明：取消预约后，返还服务次数，可在待使用中查看
            </view>
            <form @submit="formSubmit" catchreset="formReset">
                <view class="pageMiddle">
                    <view>
                        <view class="cancelReason">
                            <label style="color: #333; font-size: 36rpx;margin-bottom: 30rpx;">取消原因</label>
                            <van-field :value="reasonType" placeholder="请选择取消原因" disabled is-link  @click.native="showReasonType" />
                        </view>
                        <view class="judgeTips">
                            <view>
                                <label style="color: #333; font-size: 36rpx;margin-bottom: 30rpx;">具体说明</label>
                                <van-field :value="cancelBookedInfo.remark"  type="textarea" placeholder="请输入取消具体说明" autosize maxlength="200" @input="handleInput" />
                                <!-- <textarea placeholder="请输入取消具体说明" :value="cancelBookedInfo.remark"
                                    placeholder-style="font-size: 12px;color: #888888;" :disable-default-padding="true"
                                    @input="handleInput" auto-focus="true" confirm-type="done" maxlength="200"
                                    autoHeight
                                    custom-style="font-size: 12px;line-height:1.5; color:#111111;"></textarea> -->
                            </view>
                        </view>
                        <view class="uploadPic">
                            <view class="preview-list">
                                <view v-for="(file, fIndex) in fileList" :key="fIndex"
                                    class="preview-item">
                                    <image :src="file.url" class="preview-image"
                                        @click="previewImage(file.localPath || file.url)">
                                    </image>
                                    <view class="delete-icon" @click="deleteImage(fIndex)">×</view>
                                </view>
                            </view>
                            <!-- 上传按钮 -->
                            <view class="upload-btn" @click="chooseImage">
                                <image class="upload-icon"
                                    src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/uploaderPic.png"  mode="aspectFit"></image>
                                <text class="upload-text">点击上传图片（最多九张）</text>
                            </view>
                        </view>
                    </view>

                </view>

            </form>
        </scroll-view>
        <van-toast id="van-toast" />
        <template>
            <view class="bottom">
                <view>
                    <van-button type="primary" v-if="!checked" @click="gouxuan">确认取消</van-button>
                    <van-button type="primary" @click="toSubmitCancel" v-else :disabled="isSubmitting"
                    :class="{ 'disabled-btn': isSubmitting }">确认取消</van-button>
                </view>
                <view class="agreement" @click="onChange">
                    <van-checkbox style="width: 34rpx" icon-size="12px" :value="checked" @change="onChange"
                        :label-disabled="true" use-icon-slot>
                        <image @click="onChange" slot="icon" class="checked-img"
                            :src="checked ? activeIcon : inactiveIcon" />
                    </van-checkbox>
                    <view style="margin-left: 18rpx;">阅读并同意</view>
                    <view class="href" id="secrectAgreement" @tap="toAgreement">《取消预约服务协议》</view>
                </view>
            </view>
        </template>
        <cancelBookedReason :show="showReasonPopup" @closeReasonPopup="closeCancelPopup" @next="next" :reasonTypeCode="reasonTypeCode"> </cancelBookedReason>
        <cancelBooked :show="showCancel" @closeCancelPopup="closeCancelPopup" :cancelPopupRemark="cancelPopupRemark" :cancelBookedInfo="cancelBookedInfo"></cancelBooked>
    </view>
</template>
<script>
import CryptoJS from 'crypto-js'; // 确保已正确导入 CryptoJS

import cancelBookedReason from '@/mycomponents/myService/cancelBookedReason.vue';
import cancelBooked from '@/mycomponents/myService/cancelBooked.vue';

import Toast from '@/wxcomponents/vant/toast/toast'
import {previewCancelServiceApi} from '@/api/service'


export default {

    components: {
        cancelBookedReason,
        cancelBooked
    },
    data () {
        return {
            navBarTitle: '发布真实的评价',
            scrolling: false,
            subtitle:'商品评价',
            showCancel:false,
            showReasonPopup:false,
            fileList: [],
            fileUrl: "",
            show: false,
            sysFileId: null,
            message:'',
            content:'哈哈红红火火恍恍惚惚哈哈哈哈哈哈哈哈哈哈哈红红火火恍恍惚惚哈哈哈哈哈哈哈哈哈hhhhh哈哈红红火火恍恍惚惚哈哈哈哈哈哈哈哈哈', // 输入框内容  评论内容
            checked: false,
            inactiveIcon:
            'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/notChecked1126.png',
            activeIcon:
            'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/goodsChecked1126.png',       
            params:undefined, //接受从路由传过来的参数
            // productInfo:{
            //     content: '', // 追评内容
            //     fileList: [] // 追评图片
            // },
            // goodsList:[
            // {
            //         Id: 11,
            //         imgurl: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/judge01.png',
            //         title: '黄芪杞姜枣糕红枣',
            //         price: '15',
            //         num: '1',
            //         score: 190,
            //         money: '120',
            //         specs: '口味一：五斤装',
            //         isShouQing: false,
            //         isXiajia: false
            //     },
            //     {
            //         Id: 12,
            //         imgurl: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/judge01.png',
            //         title: '黄芪杞姜枣糕红枣枸杞 口味一：五斤装',
            //         price: '16',
            //         num: '1',
            //         score: 190,
            //         money: '120',
            //         specs: '口味一：五斤装',
            //         isShouQing: false,
            //         isXiajia: false
            //     },
            // ],
            // fileList: [], // 图片列表
            commentId:undefined,
            params:null,
            reasonType:undefined,//原因类型
            reasonTypeCode:undefined, //取消原因对应的code英文
            cancelPopupRemark:'',//取消预约对应的弹窗内容
            ifDeduct:false,//是否免责
            cancelBookedInfo:{
                reservationId:undefined, //预约id
                // fileList: [], // 图片列表
                remark: '', // 备注 具体原因
                reason:undefined, //取消原因
                attachment:'',//附件  图片数组转为字符串
            }, //取消预约信息
            isSubmitting: false, // 提交中
            submitTimer: null,
            employeeInfo:{
                avatarUrl: "https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/userAvatarUrl/1747962474260_o2phmu7kyos.jpeg",
                contactPhone: "15735104035",
                id: "1924374129297477633",
                labels: [{ subjectId: "1924374129297477633", id: "1923673598621298689", name: "诚实守信", sort: 1 }],
                name: "王女士",
                other: "<p>2</p>",
                providerId: "1923329273242529794",
                providerName: "燕子家政",
                region: "山西省 运城市 盐湖区",
                replayCount: 0,
                serviceCount: 4,
                sex: 0,
                workYear: "10.0",
            },
            reservationId:''
        }

    },

    computed: {},

    watch: {},
    onLoad (data ) {
        if(data && data.params){
            this.params = JSON.parse(decodeURIComponent(data.params))
            console.log(this.params,'params')
            this.cancelBookedInfo.reservationId = this.params.reservationId
            this.reservationId = this.params.reservationId
        }
    },
    onReady () {
    },

    methods: {
        // 滑动
        scrollPage (e) {
            console.log(e.detail.scrollTop, this.scrolling)
            if (e.detail.scrollTop > 25 && !this.scrolling) {
                this.scrolling = true
            } else if ((e.detail.scrollTop <= 25 && this.scrolling) || (e.detail.scrollTop <= 25 && !this.scrolling)) {
                this.scrolling = false
            }
        },
        // 返回键
        onClickLeft () {
            this.params.actStatus = 1
            uni.navigateTo({
                url: '/pages/myService/otherStatusService?params=' +
                encodeURIComponent(JSON.stringify(this.params))
            })
        },

        // 显示弹窗
        showReasonType(){
            // debugger
            // console.log('---')
            this.showReasonPopup=true
        },
        // 关闭弹窗
        closeCancelPopup(){
            this.showCancel=false
            this.showReasonPopup=false
        },
        next(selectedReasonType){
            this.reasonType = selectedReasonType.desc
            this.reasonTypeCode = selectedReasonType.code
            this.cancelBookedInfo.reason = selectedReasonType.code
        },

        handleInput(e) {
            console.log('输入框输入的内容是：',e, e.detail);
            const value=e.detail
            if (value.length > 200) {
                wx.showToast({
                    title: '超出字数限制',
                    icon: 'none'
                });
                return;
            }
            this.cancelBookedInfo.remark= e.detail
        },
        gouxuan() {
            if (!this.checked) {
                Toast('请先勾选取消预约服务协议')
                return false
            }
        },
        // 取消预约须知
        onChange(e) {
            if (e.target.id !== 'secrectAgreement') {
                this.checked = !this.checked
            }
        },
        toAgreement(){
        
            uni.navigateTo({
                url: '/pages/other/cancellationAgreement?params=' +
                    encodeURIComponent(JSON.stringify(this.params))
            })
        },
        // 取消预约按钮
        toSubmitCancel() {
            if (this.isSubmitting) return;
            this.isSubmitting = true;
            clearTimeout(this.submitTimer);
            if (!this.reasonType || !this.cancelBookedInfo.reason) {
                Toast('请选择取消原因')
                this.isSubmitting = false;
                return
            }
            this.submitTimer = setTimeout(async () => {
                try {
                    if (this.fileList.length > 0) {
                        this.cancelBookedInfo.attachment = this.fileList
                            .map(file => file.url)
                            .join(',');
                    }
                    console.log(this.cancelBookedInfo, 'cancelBookedInfo')

                    const res = await previewCancelServiceApi({
                        reservationId: this.params.reservationId,
                    })

                    console.log(res, 'previewCancelServiceApi')
                    if (res.code === 200) {
                        // 抵扣 免责次数 ifDeduct  为false 是不能抵扣    为true 可以抵扣
                        // 违约金额 penalty  为0 不需要付钱    不为0 需要付钱
                        if (Number(res.data.penalty) > 0 || res.data.ifDeduct == false) {
                            Toast('取消预约成功，退款金额为' + res.data.penalty + '元')
                            uni.navigateTo({
                                url: '/pages/myService/cancelPayDetail?params=' +
                                    encodeURIComponent(JSON.stringify(this.params))
                            })
                        } else {
                            this.cancelPopupRemark = res.data.cancelRemark
                            this.showCancel = true
                            this.ifDeduct = res.data.ifDeduct //是否免责
                        }
                    }
                } catch (error) {
                    console.error('提交失败:', error);
                    Toast('提交失败，请重试');
                } finally {
                    this.isSubmitting = false;
                    clearTimeout(this.submitTimer);
                }
            }, 500); // 设置500毫秒防抖间隔

        },
        async uploadToOSS(file) {
            const OSS_CONFIG = {
                region: 'oss-cn-beijing',
                accessKeyId: 'LTAI5t977yzTgy3KuHsZpNGp',
                accessKeySecret: '3XClQa1PDAqqHyK1avhz5npkhN7Uel',
                bucket: '17lelife-bucket',
                host: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/',
                dir: 'WeChat-App-Picture/followComment/images/'
            };

            try {
                // 强化文件路径校验
                const fileRealPath = file.tempFilePath || file.path || file.url;
                if (!fileRealPath) {
                    throw new Error('无法获取有效文件路径，请重新选择文件');
                }

                // 安全获取文件扩展名
                const getExtension = () => {
                    return file.type?.split('/')[1] ||
                        file.name?.split('.').pop() ||
                        fileRealPath.split('.').pop() ||
                        'jpg';
                };

                // 生成唯一文件名
                const fileName = `${Date.now()}_${Math.random()
                    .toString(36)
                    .substr(2, 12)}.${getExtension().toLowerCase()}`;
                const filePath = `${OSS_CONFIG.dir}${fileName}`;

                // 生成安全策略
                const generatePolicy = () => {
                    const policy = {
                        expiration: new Date(Date.now() + 3600000).toISOString(),
                        conditions: [
                            ["content-length-range", 0, 10485760], // 10MB限制
                            ["starts-with", "$key", OSS_CONFIG.dir]
                        ]
                    };
                    return CryptoJS.enc.Base64.stringify(
                        CryptoJS.enc.Utf8.parse(JSON.stringify(policy))
                    );
                };

                // 生成签名
                const policy = generatePolicy();
                const signature = CryptoJS.HmacSHA1(policy, OSS_CONFIG.accessKeySecret)
                    .toString(CryptoJS.enc.Base64);

                // 执行上传
                const uploadResult = await new Promise((resolve, reject) => {
                    uni.uploadFile({
                        url: OSS_CONFIG.host,
                        filePath: fileRealPath,
                        name: 'file',
                        formData: {
                            key: filePath,
                            policy: policy,
                            OSSAccessKeyId: OSS_CONFIG.accessKeyId,
                            signature: signature,
                            success_action_status: '200'
                        },
                        success: (res) => {
                            if (res.statusCode === 200) {
                                resolve(`${OSS_CONFIG.host}${filePath}`);
                            } else {
                                reject(new Error(`上传失败，状态码：${res.statusCode}`));
                            }
                        },
                        fail: (err) => {
                            reject(new Error(`上传请求失败：${err.errMsg}`));
                        }
                    });
                });

                return uploadResult;
            } catch (error) {
                console.error('OSS上传失败详情:', {
                    error,
                    fileObject: file,
                    pathAttempts: {
                        tempFilePath: file.tempFilePath,
                        path: file.path,
                        url: file.url
                    }
                });
                throw new Error(`文件上传失败：${error.message}`);
            }
        },
        async chooseImage() {
            try {
                uni.showLoading({ title: '上传中...' });
                const res = await uni.chooseImage({
                    count: 9 - this.fileList.length,
                    sizeType: ['compressed'],
                    sourceType: ['album', 'camera']
                });

                // 强化去重逻辑
                const uniqueFiles = res.tempFilePaths.filter(path => {
                    return !this.fileList.some(f =>
                        f.url === path || f.url.includes(path.split('/').pop())
                    );
                });

                const uploadPromises = uniqueFiles.map(async (filePath) => {
                    const ossUrl = await this.uploadToOSS({
                        tempFilePath: filePath,
                        path: filePath,
                        type: res.tempFiles[0].type
                    });
                    return {
                        url: ossUrl,
                        status: 'done',
                        isImage: true,
                        localPath: filePath
                    };
                });

                const newFiles = await Promise.all(uploadPromises);
                this.fileList = [...this.fileList, ...newFiles].slice(0, 9);

            } catch (error) {
                uni.showToast({ title: error.message || '上传失败', icon: 'none' });
            } finally {
                uni.hideLoading();
            }
        },

        deleteImage(index) {
            this.fileList.splice(index, 1);
        },
        previewImage(currentUrl) {
            uni.previewImage({
                current: currentUrl,
                urls: this.fileList.map(file => file.url),
                fail: (err) => {
                    console.error('预览失败:', err);
                }
            });
        },

        // // 确认按钮
        // async submitFollowComment(event) {//点击提交按钮上传设置banner图数据
        //     try {
        //         if (!this.productInfo.content || this.productInfo.content.length < 10) {
        //             return uni.showToast({
        //                 title: '评价内容不能少于10个字',
        //                 icon: 'none'
        //             });
        //         }

        //         const params = {
        //             commentId: this.commentId,
        //             content: this.productInfo.content,
        //             commentImgUrls: this.fileList.map(f => f.url),
        //             // goodsId: this.productInfo.productId, // 添加商品ID
        //             rating: this.valueStar,
        //             isAnonymous: this.isAnonymous ? 1 : 0,
        //         };

        //         const res = await submitFollowupsApi(params);
        //         uni.showToast({ title: '提交成功' });
        //         setTimeout(() => uni.navigateBack(), 1500);

        //     } catch (error) {
        //         uni.showToast({
        //             title: error.message || '提交失败',
        //             icon: 'none'
        //         });
        //     }
        // },


    }

}
</script>
<style lang="scss" scoped>

.content {
    background-color: #ffffff;
    display: flex;
    flex-direction:column;
    overflow:hidden;
    box-sizing: border-box;
    height:100vh;
}
.scroll-content {
    flex: 1;
    height: 1px;
}

.pageTop{
    width: 100%;
    background: #fff5ef;
    padding: 24rpx 48rpx;
    font-size: 24rpx;
    text-align: left;
    color: #ff6203;
}


.pageMiddle{
    padding-top: 40rpx;
    padding-left: 48rpx;
    padding-right: 48rpx;
    padding-bottom: 160rpx;
}

.judgeTips{
    padding: 48rpx 0rpx 14rpx 0rpx;
    font-size: 24rpx;
    text-align: left;
    color: #888888;
}
.uploadPic{
    margin-top:36rpx;
    display: flex;
    // align-items: center;
    flex-wrap: wrap;
    gap: 5px;
}
.uploader{
    background-color: #f9f9f9;
    padding: 24px 12px;
    border-radius: 25px;
    border:1px dashed #f9f9f9;
}
.text{
    font-size: 24rpx;
    color: #888888;
    line-height: 24rpx;
}

.overallEvaluation{
    margin-top: 24px;
    display: flex;
    align-items: center;
}
.icon{
    display: flex;
}
.icon img{
    margin-right: 25px;
}

.niming{
    display: flex;
    margin-top: 12px;
}
.radioBox{
    display: flex;
    align-items: center;
}
// 上传图片
.custom-uploader {
    padding: 15px;
}

.upload-btn {
    width: 208rpx;
    height: 208rpx;
    border: 1px dashed #ddd;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-bottom: 15px;
    background-color: #f0f0f0;
}

.upload-icon {
    width: 40rpx;
    height: 34rpx;
}

.upload-text {
    font-size: 24rpx;
    color: #888888;
    margin-top: 8px;
    text-align: center;
    width: 80%;
}

.preview-list {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
}

.preview-item {
    position: relative;
    width: 208rpx;
    height:208rpx;
    border-radius: 8px;
    overflow: hidden;
    margin-bottom: 20rpx;
}

.preview-image {
    width: 100%;
    height: 100%;
}

.delete-icon {
    position: absolute;
    top: 0;
    right: 0;
    width: 24px;
    height: 24px;
    background: rgba(0,0,0,0.5);
    color: white;
    text-align: center;
    line-height: 24px;
    border-radius: 0 0 0 8px;
}
::v-deep .van-nav-bar__left {
    width: 56px;
    height: 44px;
}

::v-deep #navBar .van-icon {
    color: #242629 !important;
}

// ::v-deep .van-icon-arrow{
//     color:#FF6203 !important ;
// }

:v-deep .van-uploader{
    border-radius: 4px !important;
}

.r20{
    margin-right: 20px;
}
.l6{
    margin-left: 6px;
}
// 报名
.agreement{
    // padding: 32rpx 48rpx 0px 48rpx;
    padding: 32rpx 0rpx 0px 0;
}
.agreement {
  height: 44rpx;
  line-height: 44rpx;
  font-size: 24rpx;
  color: #111111;
  display: flex;
  align-items: center;

  view{
    line-height: 24rpx;
    font-size: 24rpx;
  }
  .href {
    color: #ff6203;
    }
}


.checked-img {
  height: 34rpx;
  width: 34rpx;
  margin-top: 4px;
  margin-right: 18rpx;
}
button::after{
  border: none;
}
.button-hover{
  background-color: transparent;
}
textarea{
    min-height: 12px !important;
    line-height: 1.5 !important;
    color:#111111 !important;
}
::v-deep .van-uploader__upload-text {
    text-align: center !important;
}
.bottom{
    padding: 0rpx 48rpx;
    padding-bottom: calc(0rpx + env(safe-area-inset-bottom));

}
// 取消预约
::v-deep .van-button--primary {
  width: 100%;
  margin-top: 32rpx;
  height: 86rpx;
  border-radius: 50rpx;
  background: #ff6203;
}

::v-deep .van-cell {
    padding: 10px 0px;
}
::v-deep .van-cell:after {
    // border-bottom: 1px solid #ebedf0;
    // bottom: 0;
    // box-sizing: border-box;
    // content: " ";
    left: 0px !important;
    // pointer-events: none;
    // position: absolute;
    right: 0px !important;
    // transform: scaleY(.5);
    // transform-origin: center;
    // border-bottom-width: 1px;
    // border-bottom-style: solid;
    // border-bottom-color: rgb(235, 237, 240);
    width: 100%;
}
::v-deep .van-icon-arrow {
    color: #242629 !important;
}
::v-deep .van-field__control--disabled {
    color: #333333 !important;
}

.disabled-btn {
    // background-color: #cccccc !important;
    border-color: #cccccc !important;
}
</style>
